// __PUBLIC__/js/page/admin/apps/appslist
require(['../../common'], function() {
  require(['apps.appslist'])
})

define('apps.appslist', [
  'jquery',
  'page/grid'
], function($, Grid) {
  'use strict';

  var $table = $('.table')
  var mygrid = new Grid($table)
  mygrid.init()


    function setStatus(app_id, status) {
      $.post(APP + '?app=admin&m=Apps&a=setStatus', {
        app_id: app_id,
        status: status
      }, function(res) {
        if (res === '1') {
          alert('保存成功');
          var statusArray = ['关闭', '默认', '可选'];
          $('#status_' + app_id).html(statusArray[status]);
          statusArray[status] = '';
          var html = '';
          for (var s in statusArray) {
            if (statusArray[s] == '') continue;
            html += '<a href="javascript:void(0);" id="J_appStatus" data-key="' + s + '" data-appid="' + app_id + '">设为' + statusArray[s] + '&nbsp;</a> ';
          }
          $('#setStatus_' + app_id).html(html);
        } else {
          alert('保存失败');
        }
      });
    }

    function move(id, el, index, nextIndex, direction) {
      var baseid = direction == 'up' ? $(el).closest('tr').prev().data('id') : $(el).closest('tr').next().data('id');
      if (baseid) {
        $.post(APP + '?app=admin&m=Apps&a=setAppOrder', {
          app_id: id,
          baseid: baseid
        }).done(function(res) {
          if (res === '1') {
            mygrid.swap(index, nextIndex)
          }
        })
      }
    }

  $table.on('click', '.moveup', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }
    
    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) - 1), 'up')
  }).on('click', '.movedown', function(e) {
    if ($(this).hasClass('disabled')) {
      return false
    }

    move($(this).closest('tr').data('id'), this, mygrid.getIndex(this), Number(mygrid.getIndex(this) + 1), 'down')
  }).on('click', '#J_appStatus', function(e) {
    e.preventDefault()

    var appId = $(this).data('appid'),
      status = $(this).data('key')

    setStatus(appId, status)
  })

})